package com.zin.viewpagerfragment;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import entity.NewsData;
import util.Utils;

public class StartActivity extends AppCompatActivity {
    private TextView textView;
    Timer timer;
    TimerTask timetask;
  Handler handler=new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        Utils.init(this);//初始化
        setContentView(R.layout.activity_start);
        //  textView= (TextView) findViewById(R.id.textone);

        timer = new Timer();
        timetask = new TimerTask() {
            @Override
            public void run() {
                goNext();
            }
        };

        if (Utils.hasConnected()){
            getJsonData();   //有网络
        }
        else {
            timer.schedule(timetask, 2000); //定时器
        }


    }

    private void writeJson(String strjson){

        File dir=new File(Constans.SD_NEWS_DIR);
        if (!dir.exists()){
            dir.mkdir();
        }
        Utils.writeFileSdcardFile(Constans.SD_NEWS_CAT,strjson);

    }



    private void getJsonData() {


        new HttpUtils().send(HttpRequest.HttpMethod.GET,
                "http://wangyi.butterfly.mopaasapp.com/news/api?type=war&page=1&limit=12",
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String json = responseInfo.result;

                        writeJson(json);
                        //保存json文件


                     //   timer.schedule(timetask, 2000); //定时器
                        handler.postDelayed(timetask,2000);
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {

                         Utils.show("当前网络不可访问");
                        timer.schedule(timetask, 2000);
                    }
                });

    }

    private void goNext() {

        startActivity(new Intent(this, MainActivity.class));
        finish();


    }


}
